package com.tsoj.tsojquestionservice.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.tsoj.common.ErrorCode;
import com.tsoj.constant.CommonConstant;
import com.tsoj.context.ThreadLocalContext;
import com.tsoj.exception.BusinessException;
import com.tsoj.exception.ThrowUtils;
import com.tsoj.model.dto.question.*;
import com.tsoj.model.po.Question;
import com.tsoj.model.po.User;
import com.tsoj.model.vo.QuestionVO;
import com.tsoj.model.vo.UserVO;
import com.tsoj.tsojquestionservice.mapper.QuestionMapper;
import com.tsoj.tsojquestionservice.service.QuestionService;
import com.tsoj.tsojserviceclient.service.UserFeignClient;
import com.tsoj.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author 孙金硕
* @description 针对表【question(题目)】的数据库操作Service实现
* @createDate 2025-04-15 09:58:00
*/
@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question>
    implements QuestionService {

    private static final Gson GSON = new Gson();
    @Resource
    private UserFeignClient userFeignClient;



    @Override
    public Long addQuestion(QuestionAddRequest questionAddRequest) {
        Question question = new Question();
        BeanUtils.copyProperties(questionAddRequest, question);
        //转换类型
        List<String> tags = questionAddRequest.getTags();
        List<JudgeCase> judgeCase = questionAddRequest.getJudgeCase();
        JudgeConfig judgeConfig = questionAddRequest.getJudgeConfig();
        if (tags != null) {
            question.setTags(JSONUtil.toJsonStr(tags));
        }
        if (judgeCase != null) {
            question.setJudgecase(JSONUtil.toJsonStr(judgeCase));
        }
        if (judgeConfig != null) {
            question.setJudgeconfig(JSONUtil.toJsonStr(judgeConfig));
        }
        //进行进行合法性校验 对question进行校验
        if (question == null) {
            throw new RuntimeException("参数为空");
        }
        legal(question);
        Long userId = ThreadLocalContext.getUserId();
        question.setUserid(userId);
        //设置初始评论数
        question.setThumbnum(0);
        //设置初始点赞数
        question.setFavournum(0);
        boolean save = this.save(question);
        if (!save) {
            throw new RuntimeException("添加失败");
        }

        return question.getId();
    }

    //更新题目
    @Override
    public Boolean updateQuestion(QuestionUpdateRequest updateRequest) {

        //进行参数转换和验证
        List<String> tags = updateRequest.getTags();
        List<JudgeCase> judgeCase = updateRequest.getJudgeCase();
        JudgeConfig judgeConfig = updateRequest.getJudgeConfig();
        Question question = new Question();
        BeanUtils.copyProperties(updateRequest, question);
        if (tags != null) {
            question.setTags(GSON.toJson(tags));
        }
        if (judgeCase != null) {
            question.setJudgecase(GSON.toJson(judgeCase));
        }
        if (judgeConfig != null) {
            question.setJudgeconfig(GSON.toJson(judgeConfig));
        }
        //进行参数输入合法性验证
        legal(question);
        boolean b = this.updateById(question);
        return b;
    }
    //进行脱敏处理
    @Override
    public QuestionVO handle(Question question) {
        //进行VO处理
        QuestionVO questionVO = QuestionVO.objToVo(question);
        //进行关联性查询
        Long userid = question.getUserid();
        if (userid != null) {
            User user = userFeignClient.getById(userid);
            UserVO userVO = userFeignClient.getUserVO(user);
            questionVO.setUserVO(userVO);
        }
        return questionVO;
    }
    //拿到查询条件
    @Override
    public Wrapper<Question> getQueryWrapper(QuestionQueryRequest questionQueryRequest) {
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        if(questionQueryRequest == null){
            return queryWrapper;
        }
        Long id = questionQueryRequest.getId();
        String title = questionQueryRequest.getTitle();
        String content = questionQueryRequest.getContent();
        List<String> tags = questionQueryRequest.getTags();
        String answer = questionQueryRequest.getAnswer();
        Long userId = questionQueryRequest.getUserId();
        String sortField = questionQueryRequest.getSortField();
        String sortOrder = questionQueryRequest.getSortOrder();
        //拼接查询条件
        queryWrapper.like(StringUtils.isNotBlank(title), "title", title);
        queryWrapper.like(StringUtils.isNotBlank(content), "content", content);
        queryWrapper.like(StringUtils.isNotBlank(answer), "answer", answer);
        if(CollectionUtils.isNotEmpty(tags)){
            for(String tag : tags){
                queryWrapper.like("tags","\"" + tag + "\"");
            }
        }
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq("isDelete",false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }
    //进行批量数据脱敏处理
    @Override
    public Page<QuestionVO> queryVO(Page<Question> page) {
        List<Question> questionList = page.getRecords();
        Page<QuestionVO> questionVOPage = new Page<>(page.getCurrent(), page.getSize());
        if(CollectionUtils.isEmpty(questionList)){
            return questionVOPage;
        }
        //进行关联查询封装用户信息
        //将用户id进行查询去重
        Set<Long> userIdSet = questionList.stream().map(Question::getUserid).collect(Collectors.toSet());
        //将用户id分类到具体的User进行查询
        Map<Long,List<User>> userIdUSerListMap =    userFeignClient.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        //填充信息 todo 返回研读
        List<QuestionVO> questionVOList = questionList.stream().map(question -> {
            QuestionVO questionVO = QuestionVO.objToVo(question);
            Long userid = question.getUserid();
            User user = null;
            if(userIdUSerListMap.containsKey(userid)){
                user = userIdUSerListMap.get(userid).get(0);
            }
            questionVO.setUserVO(userFeignClient.getUserVO(user));
            return questionVO;
        }).collect(Collectors.toList());
        questionVOPage.setRecords(questionVOList);
        return questionVOPage;
    }

    /**
     * 校验题目是否合法
     * @param question
     * @param add
     */
    @Override
    public void validQuestion(Question question, boolean add) {
        if (question == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String title = question.getTitle();
        String content = question.getContent();
        String tags = question.getTags();
        String answer = question.getAnswer();
        String judgeCase = question.getJudgecase();
        String judgeConfig = question.getJudgeconfig();
        // 创建时，参数不能为空
        if (add) {
            ThrowUtils.throwIf(StringUtils.isAnyBlank(title, content, tags), ErrorCode.PARAMS_ERROR);
        }
        // 有参数则校验
        if (StringUtils.isNotBlank(title) && title.length() > 80) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "标题过长");
        }
        if (StringUtils.isNotBlank(content) && content.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "内容过长");
        }
        if (StringUtils.isNotBlank(answer) && answer.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "答案过长");
        }
        if (StringUtils.isNotBlank(judgeCase) && judgeCase.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "判题用例过长");
        }
        if (StringUtils.isNotBlank(judgeConfig) && judgeConfig.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "判题配置过长");
        }
    }


    //合法验证
    private static void legal(Question question) {
        String title = question.getTitle();
        String content = question.getContent();
        String tag = question.getTags();
        String answer = question.getAnswer();
        String judgecase = question.getJudgecase();
        String judgeconfig = question.getJudgeconfig();

        //进行参数内容校验
        // 有参数则校验
        if (StringUtils.isNotBlank(title) && title.length() > 80) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "标题过长");
        }
        if (StringUtils.isNotBlank(content) && content.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "内容过长");
        }
        if (StringUtils.isNotBlank(answer) && answer.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "答案过长");
        }
        if (StringUtils.isNotBlank(judgecase) && judgecase.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "判题用例过长");
        }
        if (StringUtils.isNotBlank(judgeconfig) && judgeconfig.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "判题配置过长");
        }
    }
}

